import routes from 'config/routes';
import type { Request, Response } from 'express';

// 模拟用户数据
const users = {
  admin: {
    id: '1',
    name: '管理员',
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    email: 'admin@example.com',
    role: 'admin',
    permissions: [
      'dashboard:view',
      'dashboard:analysis:view',
      'dashboard:monitor:view',
      'dashboard:workplace:view',
      'form:view',
      'form:basic:view',
      'form:step:view',
      'form:advanced:view',
      'list:view',
      'list:table:view',
      'list:basic:view',
      'list:card:view',
      'profile:view',
      'profile:basic:view',
      'profile:advanced:view',
      'account:view',
      'account:center:view',
      'account:settings:view',
      'result:view',
      'exception:view',
    ],
  },
  user: {
    id: '2',
    name: '普通用户',
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    email: 'user@example.com',
    role: 'user',
    permissions: [
      'dashboard:view',
      'dashboard:analysis:view',
      'dashboard:workplace:view',
      'form:view',
      'form:basic:view',
      'account:view',
      'account:center:view',
    ],
  },
  guest: {
    id: '3',
    name: '访客',
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    email: 'guest@example.com',
    role: 'guest',
    permissions: [
      'dashboard:view',
      'dashboard:analysis:view',
    ],
  },
};

// 模拟登录
function login(req: Request, res: Response) {
  const { username, password } = req.body;

  // 简单验证
  if (!username || !password) {
    res.status(400).json({
      code: 400,
      message: '用户名和密码不能为空',
    });
    return;
  }

  // 模拟验证逻辑
  const user = users[username as keyof typeof users];

  if (!user) {
    res.status(401).json({
      code: 401,
      message: '用户名或密码错误',
    });
    return;
  }

  // 生成模拟 token
  const token = `mock_token_${username}_${Date.now()}`;

  res.json({
    code: 200,
    message: '登录成功',
    data: {
      token,
      user,
    },
  });
}

// 获取当前用户信息（从 token 解析）
function getCurrentUser(req: Request, res: Response) {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    res.status(401).json({
      code: 401,
      message: '未登录',
    });
    return;
  }

  // 从 token 中解析用户名
  const username = token.split('_')[2];
  const user = users[username as keyof typeof users] || users.user;

  res.json({
    code: 200,
    message: '成功',
    data: user,
  });
}

// 获取用户权限列表
function getUserPermissions(req: Request, res: Response) {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    res.status(401).json({
      code: 401,
      message: '未登录',
    });
    return;
  }

  // 从 token 中解析用户名
  const username = token.split('_')[2];
  const user = users[username as keyof typeof users] || users.user;

  res.json({
    code: 200,
    message: '成功',
    data: {
      permissions: user.permissions,
      role: user.role,
    },
  });
}

// 根据用户权限返回路由配置
function getRoutesByPermission(req: Request, res: Response) {
  const token = req.headers.authorization?.replace('Bearer ', '');

  // if (!token) {
  //   res.status(401).json({
  //     code: 401,
  //     message: '未登录',
  //   });
  //   return;
  // }

  // // 从 token 中解析用户名
  // const username = token.split('_')[2];
  // const user = users[username as keyof typeof users] || users.user;
  // const permissions = user.permissions;

  // 根据权限过滤路由
  // const routes = [];

  // // Dashboard
  // if (permissions.includes('dashboard:view')) {
  //   const dashboardRoutes = [];
  //   if (permissions.includes('dashboard:analysis:view')) {
  //     dashboardRoutes.push({
  //       name: 'analysis',
  //       path: '/dashboard/analysis',
  //       component: './dashboard/analysis',
  //     });
  //   }
  //   if (permissions.includes('dashboard:monitor:view')) {
  //     dashboardRoutes.push({
  //       name: 'monitor',
  //       path: '/dashboard/monitor',
  //       component: './dashboard/monitor',
  //     });
  //   }
  //   if (permissions.includes('dashboard:workplace:view')) {
  //     dashboardRoutes.push({
  //       name: 'workplace',
  //       path: '/dashboard/workplace',
  //       component: './dashboard/workplace',
  //     });
  //   }

  //   if (dashboardRoutes.length > 0) {
  //     routes.push({
  //       path: '/dashboard',
  //       name: 'dashboard',
  //       icon: 'dashboard',
  //       routes: [
  //         {
  //           path: '/dashboard',
  //           redirect: '/dashboard/analysis',
  //         },
  //         ...dashboardRoutes,
  //       ],
  //     });
  //   }
  // }

  // // Form
  // if (permissions.includes('form:view')) {
  //   const formRoutes = [];
  //   if (permissions.includes('form:basic:view')) {
  //     formRoutes.push({
  //       name: '基础表单',
  //       path: '/form/basic-form',
  //       component: './form/basic-form',
  //     });
  //   }
  //   if (permissions.includes('form:step:view')) {
  //     formRoutes.push({
  //       name: '分步表单',
  //       path: '/form/step-form',
  //       component: './form/step-form',
  //     });
  //   }
  //   if (permissions.includes('form:advanced:view')) {
  //     formRoutes.push({
  //       name: '高级表单',
  //       path: '/form/advanced-form',
  //       component: './form/advanced-form',
  //     });
  //   }

  //   if (formRoutes.length > 0) {
  //     routes.push({
  //       path: '/form',
  //       name: '表单页',
  //       icon: 'form',
  //       routes: formRoutes,
  //     });
  //   }
  // }

  // // List
  // if (permissions.includes('list:view')) {
  //   const listRoutes = [];
  //   if (permissions.includes('list:table:view')) {
  //     listRoutes.push({
  //       name: '表格列表',
  //       path: '/list/table-list',
  //       component: './list/table-list',
  //     });
  //   }
  //   if (permissions.includes('list:basic:view')) {
  //     listRoutes.push({
  //       name: '基础列表',
  //       path: '/list/basic-list',
  //       component: './list/basic-list',
  //     });
  //   }
  //   if (permissions.includes('list:card:view')) {
  //     listRoutes.push({
  //       name: '卡片列表',
  //       path: '/list/card-list',
  //       component: './list/card-list',
  //     });
  //   }

  //   if (listRoutes.length > 0) {
  //     routes.push({
  //       path: '/list',
  //       name: '列表页',
  //       icon: 'table',
  //       routes: listRoutes,
  //     });
  //   }
  // }

  // // Account
  // if (permissions.includes('account:view')) {
  //   const accountRoutes = [];
  //   if (permissions.includes('account:center:view')) {
  //     accountRoutes.push({
  //       name: '个人中心',
  //       path: '/account/center',
  //       component: './account/center',
  //     });
  //   }
  //   if (permissions.includes('account:settings:view')) {
  //     accountRoutes.push({
  //       name: '个人设置',
  //       path: '/account/settings',
  //       component: './account/settings',
  //     });
  //   }

  //   if (accountRoutes.length > 0) {
  //     routes.push({
  //       path: '/account',
  //       name: '个人页',
  //       icon: 'user',
  //       routes: accountRoutes,
  //     });
  //   }
  // }




  res.json({
    code: 200,
    message: '成功',
    data: [
      {
        path: '/user',
        layout: false,
        routes: [
          {
            path: '/user/login',
            layout: false,
            name: '登录', // 对应 'menu.login': '登录'
            component: './user/login',
          },
          {
            path: '/user',
            redirect: '/user/login',
          },
          {
            name: '注册结果', // 对应 'menu.register-result': '注册结果'
            icon: 'smile',
            path: '/user/register-result',
            component: './user/register-result',
          },
          {
            name: '注册', // 对应 'menu.register': '注册'
            icon: 'smile',
            path: '/user/register',
            component: './user/register',
          },
          {
            component: '404',
            path: '/user/*',
          },
        ],
      },
      // Dashboard 路由
      {
        path: '/dashboard',
        name: '主页', // 对应 'menu.dashboard': '主页'
      
        access: 'canViewDashboard',
        routes: [
          {
            path: '/dashboard',
            redirect: '/dashboard/analysis',
          },
          {
            name: '项目主页', // 对应 'menu.dashboard.analysis': '项目主页'
            icon: 'smile',
            path: '/dashboard/analysis',
            component: './dashboard/analysis',
            access: 'canViewDashboardAnalysis',
          },
          {
            name: '监控页', // 对应 'menu.dashboard.monitor': '监控页'
            icon: 'smile',
            path: '/dashboard/monitor',
            component: './dashboard/monitor',
            access: 'canViewDashboardMonitor',
          },
          {
            name: '工作台', // 对应 'menu.dashboard.workplace': '工作台'
            icon: 'smile',
            path: '/dashboard/workplace',
            component: './dashboard/workplace',
            access: 'canViewDashboardWorkplace',
          },
        ],
      },
      {
        path: '/form',
        icon: 'form',
        name: '业财单据', // 对应 'menu.form': '业财单据'
        access: 'canViewForm',
        routes: [
          {
            path: '/form',
            redirect: '/form/basic-form',
          },
          {
            name: '认款单', // 对应 'menu.form.basic-form': '认款单'
            icon: 'smile',
            path: '/form/basic-form',
            component: './form/basic-form',
            access: 'canViewFormBasic',
          },
          {
            name: '收入确认单', // 对应 'menu.form.step-form': '收入确认单'
            icon: 'smile',
            path: '/form/step-form',
            component: './form/step-form',
            access: 'canViewFormStep',
          },
          {
            name: '付款单', // 对应 'menu.form.advanced-form': '付款单'
            icon: 'smile',
            path: '/form/advanced-form',
            component: './form/advanced-form',
            access: 'canViewFormAdvanced',
          },
          {
            name: '业财表单', // 对应 'menu.form.businessFinance-form': '业财表单'
            icon: 'smile',
            path: '/form/businessFinance-form',
            component: './form/businessFinance-form',
            access: 'canViewFormBasic',
          },
        ],
      },
      {
        path: '/list',
        icon: 'table',
        name: '资产核销', // 对应 'menu.list': '资产核销'
        access: 'canViewList',
        routes: [
          {
            path: '/list/search',
            name: '公司库', // 对应 'menu.list.search-list': '公司库'
            component: './list/search',
            routes: [
              {
                path: '/list/search',
                redirect: '/list/search/articles',
              },
              {
                name: '资金（调拨）', // 对应 'menu.list.search-list.articles': '资金（调拨）'
                icon: 'smile',
                path: '/list/search/articles',
                component: './list/search/articles',
              },
              {
                name: '资金（报账）', // 对应 'menu.list.search-list.projects': '资金（报账）'
                icon: 'smile',
                path: '/list/search/projects',
                component: './list/search/projects',
              },
              {
                name: '资金（核销）', // 对应 'menu.list.search-list.applications': '资金（核销）'
                icon: 'smile',
                path: '/list/search/applications',
                component: './list/search/applications',
              },
            ],
          },
          {
            path: '/list',
            redirect: '/list/table-list',
          },
          {
            name: '资金调拨', // 对应 'menu.list.table-list': '资金调拨'
            icon: 'smile',
            path: '/list/table-list',
            component: './table-list',
            access: 'canViewListTable',
          },
          {
            name: '往来核销', // 对应 'menu.list.basic-list': '往来核销'
            icon: 'smile',
            path: '/list/basic-list',
            component: './list/basic-list',
            access: 'canViewListBasic',
          },
          {
            name: '复合池', // 对应 'menu.list.card-list': '复合池'
            icon: 'smile',
            path: '/list/card-list',
            component: './list/card-list',
            access: 'canViewListCard',
          },
        ],
      },
      {
        path: '/profile',
        name: '租赁', // 对应 'menu.profile': '租赁'
        icon: 'profile',
        access: 'canViewProfile',
        routes: [
          {
            path: '/profile',
            redirect: '/profile/basic',
          },
          {
            name: '长期租赁资产登记信息', // 对应 'menu.profile.basic': '长期租赁资产登记信息'
            icon: 'smile',
            path: '/profile/basic',
            component: './profile/basic',
            access: 'canViewProfileBasic',
          },
          {
            name: '长期租赁资产调整信息', // 对应 'menu.profile.advanced': '长期租赁资产调整信息'
            icon: 'smile',
            path: '/profile/advanced',
            component: './profile/advanced',
            access: 'canViewProfileAdvanced',
          },
        ],
      },
      {
        name: '利息计提', // 对应 'menu.result': '利息计提'
        icon: 'CheckCircleOutlined',
        path: '/result',
        access: 'canViewResult',
        routes: [
          {
            path: '/result',
            redirect: '/result/success',
          },
          {
            name: '资产终止记录', // 对应 'menu.result.success': '资产终止记录'
            icon: 'smile',
            path: '/result/success',
            component: './result/success',
          },
          {
            name: '利息计提查询', // 对应 'menu.result.fail': '利息计提查询'
            icon: 'smile',
            path: '/result/fail',
            component: './result/fail',
          },
        ],
      },
      {
        name: '费用类型配置', // 对应 'menu.exception': '费用类型配置'
        icon: 'warning',
        path: '/exception',
        access: 'canViewException',
        routes: [
          {
            path: '/exception',
            redirect: '/exception/403',
          },
          {
            name: '403', // 对应 'menu.exception.403': '403'
            icon: 'smile',
            path: '/exception/403',
            component: './exception/403',
          },
          {
            name: '404', // 对应 'menu.exception.404': '404'
            icon: 'smile',
            path: '/exception/404',
            component: './exception/404',
          },
          {
            name: '500', // 对应 'menu.exception.500': '500'
            icon: 'smile',
            path: '/exception/500',
            component: './exception/500',
          },
        ],
      },
      {
        name: '个人页', // 对应 'menu.account': '个人页'
        icon: 'user',
        path: '/account',
        access: 'canViewAccount',
        routes: [
          {
            path: '/account',
            redirect: '/account/center',
          },
          {
            name: '个人中心', // 对应 'menu.account.center': '个人中心'
            icon: 'smile',
            path: '/account/center',
            component: './account/center',
            access: 'canViewAccountCenter',
          },
          {
            name: '个人设置', // 对应 'menu.account.settings': '个人设置'
            icon: 'smile',
            path: '/account/settings',
            component: './account/settings',
            access: 'canViewAccountSettings',
          },
        ],
      },
      {
        name: '动态路由测试', // 原配置无映射，保留中文名称
        icon: 'experiment',
        path: '/dynamic-routes-demo',
        component: './DynamicRoutesDemo',
      },
      {
        path: '/',
        redirect: '/dashboard/analysis',
      },
      {
        component: '404',
        path: '/*',
      },
    ],
  });
}

export default {
  'POST /api/login': login,
  'GET /api/currentUser': getCurrentUser,
  'GET /api/permissions': getUserPermissions,
  'GET /api/routes/permission': getRoutesByPermission,
};
